package com.turtle.security.common.exception;


import com.turtle.security.common.utils.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author turtle
 * date: 2020-05-01
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义异常处理
     *
     * @param e 异常
     * @return ApiResult
     */
    @ExceptionHandler(CustomException.class)
    public ApiResult businessException(CustomException e) {
        return ApiResult.error(e.getMessage());
    }

    /**
     * 登录账号不存在异常处理
     *
     * @param e 异常
     * @return ApiResult
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    public ApiResult handleUsernameNotFoundException(UsernameNotFoundException e) {
        log.error(e.getMessage(), e);
        return ApiResult.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     *
     * @param e 异常
     * @return ApiResult
     */
    @ExceptionHandler(BindException.class)
    public ApiResult validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        return ApiResult.error(e.getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 请求参数验证异常处理
     *
     * @param e 异常
     * @return ApiResult
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult validExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return ApiResult.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 请求参数类型验证异常处理
     *
     * @param e 异常
     * @return ApiResult
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ApiResult validExceptionHandler(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        return ApiResult.error("参数非法，请检查参数类型");
    }

    /**
     * IllegalArgumentException异常处理
     *
     * @param e 异常
     * @return ApiResult
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ApiResult validExceptionHandler(IllegalArgumentException e) {
        log.error((e.getMessage()), e);
        return ApiResult.error(e.getMessage());
    }

}
